<template>
  <Form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
    <FormItem prop="userCode">
      <Input v-model="form.userCode" placeholder="请输入用户名">
        <span slot="prepend">
          <Icon :size="16" type="ios-person"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="password">
      <Input type="password" v-model="form.password" password  placeholder="请输入密码">
        <span slot="prepend">
          <Icon :size="14" type="md-lock"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem>
      <Button @click="handleSubmit" class="lz-btn-primary" long>登录</Button>
    </FormItem>
  </Form>
</template>
<script setup>
import {login} from "@/module-base/api/login.js";
import {useLoginStore} from "@/module-base/stores/login.js";
import {computed, ref} from "vue";

const {handleLogIn} = useLoginStore()
const props = defineProps({
  userCodeRules: {
    type: Array,
    default: () => {
      return [
        {required: true, message: '账号不能为空', trigger: 'blur'}
      ]
    }
  },
  passwordRules: {
    type: Array,
    default: () => {
      return [
        {required: true, message: '密码不能为空', trigger: 'blur'}
      ]
    }
  }
})
const emit = defineEmits(['on-success-valid'])
const form = ref({
  userCode: '',
  password: ''
})
const rules = computed(() => {
  return {
    userCode: props.userCodeRules,
    password: props.passwordRules
  }
})
const loginForm = ref(null)

async function handleSubmit() {
  const validRs=await loginForm.value.validate()
  if (validRs) {
    const data = {
      userCode: form.value.userCode,
      password: form.value.password
    };
    const res = await login(data)
    if (res.success) {
      // 登录成功后，维护全局变量
      await handleLogIn(res)
      // 调用父组件事件
      emit('on-success-valid')
    }

  }
}
</script>
